package com.goldman.aplt.service.parameter;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.goldman.aplt.base.type.ComAp;
import com.goldman.aplt.entity.parameter.AppSystemParameter;
import com.goldman.aplt.repo.parameter.AppSystemParameterMapper;
import com.goldman.aplt.util.CommUtil;
import com.goldman.base.common.sys.exception.BusinessException;
import com.goldman.http.common.s2s.model.ErrorCode;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@CacheConfig(cacheNames = "${systemId}:AppSystemParameterService")
@Service
public class AppSystemParameterService extends ServiceImpl<AppSystemParameterMapper, AppSystemParameter> {
    private static final String WILDCARD = "*";

    @Cacheable
    public AppSystemParameter selOne(String mainKey, String subKey) {
        return lambdaQuery().eq(AppSystemParameter::getParmCode, mainKey)
                .eq(AppSystemParameter::getPrimaryKey, subKey).one();
    }

    @Cacheable
    public boolean exists(String mainKey, String subKey) {
        return selOne(mainKey, subKey) != null;
    }
    @Cacheable
    public boolean exists(String mainKey) {
        return exists(mainKey, "*");
    }
    @Cacheable
    public String getValue(String mainKey, String subKey) {
        AppSystemParameter param = selOne(mainKey, subKey);
        if(param == null || CommUtil.isNull(param.getParmValue())) {
            throw new BusinessException(ErrorCode.SYS_ERROR,"System parameters are empty.");
        }
        return param.getParmValue();
    }
    @Cacheable
    public String getValue(String mainKey) {
        return getValue(mainKey, "*");
    }

    @Cacheable
    public List<ComAp.QryParmOut> getParms(List<ComAp.QryParmIn> ins) {
        List<ComAp.QryParmOut> outs = new ArrayList<>();
        for(ComAp.QryParmIn in : ins) {
            CommUtil.fieldNotNull(in.getMainKey(), "main key");
            if(CommUtil.isNull(in.getSubKey())) {
                in.setSubKey("*");
            }
            if(exists(in.getMainKey(), in.getSubKey())) {
                AppSystemParameter param = selOne(in.getMainKey(), in.getSubKey());
                ComAp.QryParmOut out = new ComAp.QryParmOut();
                out.setMainKey(in.getMainKey());
                out.setSubKey(in.getSubKey());
                out.setValue(param.getParmValue());
                out.setDesc(param.getParmDesc());
                out.setRemark(param.getRemark());
                outs.add(out);
            }
        }
        return outs;
    }

}
